package proj.client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import proj.common.Config;
import proj.common.Request;
import proj.common.Response;

public class SocketClient {
	private Socket s;
	private ObjectInputStream oin;
	private ObjectOutputStream out;

	public SocketClient() {
		String ip = Config.getIp();
		int port = Config.getPort();
		try {
			s = new Socket(ip, port);
			oin = new ObjectInputStream(s.getInputStream());
			out = new ObjectOutputStream(s.getOutputStream());
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}

	public Response send(Request res) {
		try {
			out.writeObject(res);
			out.flush();
			out.reset();
			return (Response) oin.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new Response(false, "网络故障");

	}

	public void close() {
		if (s != null)
			try {
				s.close();
			} catch (Exception e) {
				// TODO 自动生成的 catch 块
				// e.printStackTrace();
			}
	}
}
